import re

from django.db import models

class LayoutEngine(models.Model):
    id = models.CharField(max_length=255, primary_key=True)
    vendor = models.CharField(max_length=255)

    def __unicode__(self):
        return "%s (%s)" % (self.pk, self.vendor)

class Product(models.Model):
    id = models.CharField(max_length=255, primary_key=True)
    layout_engine = models.ForeignKey(LayoutEngine)

    def __unicode__(self):
        return self.id

class Branch(models.Model):
    id = models.CharField(max_length=20, primary_key=True)
    name = models.CharField(max_length=255)
    product = models.ForeignKey(Product)

    class Meta:
        verbose_name_plural = "branches"

    def __unicode__(self):
        return "%s %s" % (self.product, self.name)

class UseragentManager(models.Manager):
    def get_by_pbp(self, product, branch, platform):
        return self.select_related().get(
            enabled=True,
            branch__product=product,
            branch__name=branch,
            platform=platform
        )

class Useragent(models.Model):
    MOZ_BUILDID_RE = re.compile("(\d{4})(\d{2})(\d{2})(\d{2})(\d{4})")
    PLATFORM_WINDOWS = 'win'
    PLATFORM_MAC = 'mac'
    PLATFORM_LINUX = 'lin'
    PLATFORM_CHOICES = (
        (PLATFORM_WINDOWS, 'Win'),
        (PLATFORM_MAC, 'Mac'),
        (PLATFORM_LINUX, 'Lin'),
    )

    id = models.CharField(max_length=100, primary_key=True)
    name = models.CharField(max_length=255)
    enabled = models.BooleanField()
    platform = models.CharField(max_length=3, choices=PLATFORM_CHOICES)
    version = models.CharField(max_length=20)
    # This is the path to the directory containing the browser.  The launching
    # class is responsible for locating the right executable to launch inside it.
    # Default browser uninstall should delete this directory.
    path = models.CharField(max_length=200)
    branch = models.ForeignKey(Branch)
    generation = models.IntegerField(default=0)

    objects = UseragentManager()

    class Meta:
        ordering = ["branch__product", "version", "platform"]

    def __unicode__(self):
        #return "%s %s %s" % (self.branch.product, self.version, self.get_platform_display())
        # transform Mozilla version string to something that fits better in the
        # tables.
        ver = self.version
        m = self.MOZ_BUILDID_RE.match(ver)
        if m:
            ver = "%s %s %s" % m.groups()[:3]
        return "%s %s %s (%s)" % (self.branch.product, self.branch.name,
                                  self.get_platform_display(), ver)

    @models.permalink
    def get_absolute_url(self):
        return ('useragent-detail', [str(self.id)])

try:
    import browsertests.main.utils
    browsertests.main.utils.redirect___file__(globals())
except:
    pass
